// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package utils;

import com.google.api.adwords.lib.AdWordsService;
import com.google.api.adwords.lib.AdWordsServiceLogger;
import com.google.api.adwords.lib.AdWordsUser;
import com.google.api.adwords.lib.ReportDate;
import com.google.api.adwords.lib.ServiceAccountantManager;
import com.google.api.adwords.lib.utils.ReportCallback;
import com.google.api.adwords.lib.utils.ReportUtils;
import com.google.api.adwords.v13.DefinedReportJob;
import com.google.api.adwords.v13.ReportInterface;

import java.io.IOException;

/**
 * This demo downloads a report synchronously or asynchronously.
 */
public class DownloadReportDemo {
  public static void main(String[] args) throws Exception{
    // Log SOAP XML request and response.
    AdWordsServiceLogger.log();

    // Get AdWordsUser from "~/adwords.properties".
    AdWordsUser user = new AdWordsUser();

    // Get ReportService.
    ReportInterface reportService = user.getService(AdWordsService.V13.REPORT_SERVICE);

    // Create report job.
    DefinedReportJob job = new DefinedReportJob();
    job.setSelectedReportType("Structure");
    job.setAggregationTypes(new String[] {"Keyword"});
    job.setStartDay(new ReportDate(2009, 0, 1).toDate());
    job.setEndDay(new ReportDate(2009, 0, 31).toDate());
    job.setName("Demo Structure Keyword Report");
    job.setSelectedColumns(new String[] {
        "Campaign", "CampaignId", "AdGroup", "AdGroupId", "Keyword",
        "KeywordId", "MaximumCPC"});

    // Validate report job.
    reportService.validateReportJob(job);

    // Schedule report job.
    long reportJobId = reportService.scheduleReportJob(job);

    final ReportUtils reportUtils = new ReportUtils(user, reportJobId);

    // Change to your file location.
    final String gzXmlPath = "/path/to/filename.xml.gz";

    // Change to use synchronous or asynchronous downloading.
    boolean useSynchronous = true;

    System.out.println("Downloading report to " + gzXmlPath + "...");

    if (useSynchronous) {
      // Download gzipped XML synchronously.
      try {
        if (reportUtils.waitForReportReady()) {
          reportUtils.downloadReport(true, gzXmlPath);
        } else {
          System.out.println("The report failed to schedule.");
        }
      } catch (IOException e) {
        System.out.println("Report did not download for reason: " + e.getMessage());
        e.printStackTrace();
      }
    } else {
      // Download gzipped XML asynchronously.
      Thread reportThread = reportUtils.whenReportReady(new ReportCallback() {
        public void onSuccess() {
          try {
            reportUtils.downloadReport(true, gzXmlPath);
          } catch (IOException e) {
            System.out.println("Report did not download for reason: " + e.getMessage());
            e.printStackTrace();
          }
        }

        public void onInterruption() {
          System.out.println("The report thread was interrupted.");
        }

        public void onFailure() {
          System.out.println("The report failed to schedule.");
        }

        public void onException(Exception e) {
          System.out.println("Report did not download for reason: " + e.getMessage());
          e.printStackTrace();
        }
      });
    }

    // Determining how much quota all these operations have consumed.
    System.out.println("Total Quota unit cost for this run: "
        + ServiceAccountantManager.getInstance().getTotalUnitCount());
  }
}
